﻿using mozhi.smarterp.Business.Enums;
using Mozhi.Abp.Domain.BasicData.Repositories;
using System;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Domain.Entities;
using Volo.Abp.Domain.Services;

namespace mozhi.smarterp.Business
{
    public class DocumentManagerBase<TEntity, TKey> : DomainService where TEntity : DocumentAggregateRoot, IEntity<TKey>
    {
        protected DocumentType _documentType;

        protected IDocumentRepository<TEntity, TKey> _repository;
        protected INumberGeneratorRepository _numberGeneratorRepository;


        public DocumentManagerBase(IDocumentRepository<TEntity, TKey> repository, INumberGeneratorRepository numberGeneratorRepository, DocumentType documentType)
        {
            _repository = repository;
            _numberGeneratorRepository = numberGeneratorRepository;
            _documentType = documentType;
        }

        public virtual async Task<string> GetNextNumberAsync()
        {
            var lastNumber = await _repository.GetLastNumberAsnyc();

            var numberGenerator = await _numberGeneratorRepository.GetAsync((int)_documentType, lastNumber ?? "");

            if (numberGenerator == null)
                throw new UserFriendlyException($"未设置类型为：{_documentType}的编码规则", "100000");

            return numberGenerator?.Number;
        }
    }
}
